package com.aimuceliang.aimuceliang;

import android.annotation.SuppressLint;
import android.app.Application;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.util.Log;

import com.aimuceliang.aimuceliang.api.ApiService;
import com.aimuceliang.aimuceliang.bean.HttpResult;
import com.aimuceliang.aimuceliang.net.HttpSubscriber;
import com.aimuceliang.aimuceliang.utils.NetUtils;
import com.aimuceliang.aimuceliang.utils.SharePreferenceUtil;
import com.aimuceliang.aimuceliang.utils.T;
import com.aimuceliang.aimuceliang.utils.XLog;

import cn.jpush.android.api.JPushInterface;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;


/**
 * Created by 何鹏 on 2016/8/4.
 * <p>
 * Application类
 */
public class MyApp extends Application {

    @SuppressLint("StaticFieldLeak")
    public static Context context;
    @SuppressLint("StaticFieldLeak")
    private static MyApp instance;
    private static ApiService mApi;
    private CompositeSubscription mCompositeSubscription;
    public static BluetoothSocket bluetoothSocket;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        context = this.getApplicationContext();
        mApi = ApiService.getApiService();//初始化ApiService
        XLog.DEBUG_MODE = Constants.DEBUG_MODE;
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        T.register(this);
        NetUtils.register(this);
        getDict();
    }

    /**
     * @return Application  Instance
     */
    public static MyApp getInstance() {
        return instance;
    }

    /**
     * @return Application  Instance
     */
    public static ApiService getApiService() {
        return mApi;
    }

    /**
     * 目前获取字典的接口，company输入任何值均可获取
     */
    private void getDict() {
        addSubscription(MyApp.getApiService().savedict(new HttpSubscriber<HttpResult>() {
            @Override
            public void onFinished() {

            }

            @Override
            public void onNext(HttpResult httpResult) {
                if (httpResult != null) {
                    if (httpResult.code.equals("0")) {
                        Log.d("GET_DICT=", "msg=" + httpResult.message + ";data=" + httpResult.data);
                        SharePreferenceUtil.saveLC(context, "LC");
                        SharePreferenceUtil.saveWC(context, "WC");
                        SharePreferenceUtil.saveTC(context, "TC");
                    }
                } else {
                    T.showShort("服务器异常，请稍后再试");
                }
            }
        }, "armo"));
    }

    private void addSubscription(Subscription subscription) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(subscription);
    }
}
